package day2_linkedlist.nowcoder;

import java.util.Scanner;

/**
 * 牛客网反转部分单链表，ACM模式
 * @author yuisama
 * @date 2022/05/08 11:08
 **/
public class Num537557_ReversePartList {
    static class Node {
        int val;
        Node next;
        public Node() {}
        public Node(int val) {
            this.val = val;
        }
    }
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        scanner.nextLine();
        String value = scanner.nextLine();
        String[] nodeValue = value.split(" ");
        Node dummyHead = new Node();
        Node tail = dummyHead;
        for (int i = 0; i < n; i++) {
            Node node = new Node(Integer.parseInt(nodeValue[i]));
            tail.next = node;
            tail = node;
        }
        String part = scanner.nextLine();
        int left = Integer.parseInt(part.split(" ")[0]);
        int right = Integer.parseInt(part.split(" ")[1]);
        Node newHead = reversePartList(dummyHead.next,left,right);
        while (newHead != null) {
            System.out.print(newHead.val + " ");
            newHead = newHead.next;
        }
    }

    /**
     * 反转从left..right区间的链表
     * @param head
     * @param left
     * @param right
     * @return
     */
    public static Node reversePartList(Node head, int left, int right) {
        Node dummyHead = new Node();
        dummyHead.next = head;
        Node prev = dummyHead;
        for (int i = 1; i < left; i++) {
            prev = prev.next;
        }
        // prev指向待反转的区间前驱，cur指向待反转的第一个节点
        Node cur = prev.next;
        for (int i = 0; i < (right - left); i++) {
            Node third = cur.next;
            // 先把next从链表中删除
            cur.next = third.next;
            // 再将next头插cur之前
            third.next = prev.next;
            prev.next = third;
        }
        return dummyHead.next;
    }
}